package com.bianguo.android.camerademo.util;

import android.media.Image;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/11/28.
 */

public class SaveImageThread implements Runnable {

    private Image mImage;
    private Handler mHandler;
    private boolean isCloseHandler;

    public SaveImageThread(Image image, Handler mHandler) {
        mImage = image;
        this.mHandler = mHandler;
    }

    public void setImage(Image mImage) {
        this.mImage = mImage;
    }

    public void setCloseHandler(boolean closeHandler) {
        isCloseHandler = closeHandler;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void run() {
        MLog.mLog("saveImageThread run");
        ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
        byte[] data = new byte[buffer.capacity()];
        buffer.get(data);
        String path = Environment.getExternalStorageDirectory() + "/CameraDemo/";
        File mImageFile = new File(path);
        if (!mImageFile.exists()) {
            boolean ret = mImageFile.mkdirs();
            assert (ret);
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String fileName = path + "IMG_" + timeStamp + ".jpg";
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            fos.write(data, 0, data.length);
            Message msg = mHandler.obtainMessage();
            msg.what = 0;
            msg.obj = fileName;
            if (!isCloseHandler) {
                mHandler.sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            mImage.close();
        }
    }
}
